package com.kdtech.analyse.news;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.AnalyseNews;
import com.kdtech.crawler.CrawlHTML;
import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.StringUtils;

/**
 * 中国网滨海高新
 * @author Persh
 *
 */
public class Sun0758NewsAnalyse implements AnalyseNews {

	private static final String[] regex={
		"http://www.sun0758.com/zq/[a-z]*/[0-9]*.html",
		"http://[a-z]*.sun0758.com/[a-z]*/[0-9]*.html",
		"http://www.sun0758.com/^(?!service)/[0-9]*.html",
		"http://[a-z]*.sun0758.com/[a-z]*/[a-z]*/[0-9]*.html",
		"http://[a-z]*.sun0758.com/[a-z]*/[a-z]*/[a-z]*/[0-9]*.html",
		"http://[a-z]*.sun0758.com/[a-z]*/[a-z]*/[0-9]*-[0-9]*-[0-9]*/[0-9]*.html",
	};


	
	public boolean isDetailPage(String url) {
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta news=new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();

		news.setUrl(url);
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);
		//title =doc.select("div#chan_newsBlk h1").text();
		title =doc.select("div.left h1").text();
		
		content=HtmlCleaner.getContentHtml(url,doc.select("div.p_center"));
		if(StringUtils.isBlank(content)){
			content=HtmlCleaner.getContentHtml(url,doc.select("div.c"));
		}
		
		String authorStr=null;
		authorStr=doc.select("div.title_body_left").text();
		author=StringUtils.substringBefore(authorStr, "时间");
		if(StringUtils.isBlank(authorStr)){
			authorStr=doc.select("div.sj").text();
			author=StringUtils.substringBetween(authorStr, "浏览：","字体大小");
		}
						
		date=DateUtils.matchDate(doc.select("div.title_body_left").text());
		if(date == null) {
			date=DateUtils.matchDate(doc.select("div.sj div.sj_left").text());
		}
		
		if(StringUtils.isBlank(title)){
		}
		news.setTitle(StringUtils.trimSpace(title));
		news.setContent(content);
		news.setAuthor(author);
		news.setDate(date);

		return news;
	}

	public static void main(String[] args) {
		Sun0758NewsAnalyse analyse=new Sun0758NewsAnalyse();
		//String url="http://www.qyxxg.com/html/2015/0908/2321537257.htm";
		String url="http://www.sun0758.com/service/14926.html";
		url = UrlArgumentTop.FromatUrl(url);
		System.out.println(UrlArgumentTop.FromatUrl(url));
		System.out.println(analyse.isDetailPage(url));
		UrlMeta meta=CrawlHTML.responseToURL(url);
		System.out.println(analyse.parserHtml(meta));
	}

	
	public NewsMeta Update(NewsMeta meta) {
		return null;
	}

	
	public boolean isNeedUpdate(){
		return false;
	}
}
